<template>
  <el-row :gutter="20">
    <el-col :span="7">
      <span class="grid-content ep-bg-purple">描述 </span>
      <el-input
          v-model="descriptionInput"
          style="width: 140px"
          placeholder="请输入商品描述"
          clearable
      />
    </el-col>
    <el-col :span="7">
      <span class="grid-content ep-bg-purple">类别 </span>
      <el-select
          v-model="categorySelect"
          placeholder="Select"
          style="width: 140px"
          clearable
      >
        <el-option
            v-for="item in categoryOptions"
            :key="item"
            :label="item"
            :value="item"
        />
      </el-select>
    </el-col>
    <el-col :span="7">
      <span class="grid-content ep-bg-purple">价格 </span>
      <el-input
          v-model="priceLow"
          style="width: 75px"
          placeholder="0"
          type="number"
      />
      至
      <el-input
          v-model="priceHigh"
          style="width: 75px"
          placeholder="0"
          type="number"
      />
    </el-col>
    <el-col :span="3">
      <el-button type="primary" @click="handleSearch">查询</el-button>
    </el-col>
  </el-row>

  <el-button class="btuuu" type="primary" @click="dialogFormVisible = true">+ 新增商品</el-button>
  <el-dialog v-model="dialogFormVisible" title="新增商品信息" width="500">
    <el-form :model="form">
      <el-form-item label="商品名" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品类别" :label-width="formLabelWidth">
        <el-select v-model="form.category" placeholder="请选择类别">
          <el-option
              v-for="item in categoryOptions"
              :key="item"
              :label="item"
              :value="item"/>
        </el-select>
      </el-form-item>
      <el-form-item label="价格" :label-width="formLabelWidth">
        <el-input v-model="form.price" autocomplete="off" />
      </el-form-item>
      <el-form-item label="库存" :label-width="formLabelWidth">
        <el-input v-model="form.stock" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品描述" :label-width="formLabelWidth">
        <el-input v-model="form.description" autocomplete="off" />
      </el-form-item>
      <el-form-item label="商品图片" :label-width="formLabelWidth">
        <el-upload
            class="upload-demo"
            drag
            :action="null"
        :http-request="uploadImage"
        :show-file-list="false"
        :before-upload="beforeUpload"
        accept="image/*"
        >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">点击或拖拽上传图片</div>
        <div v-if="form.imageURL " class="el-upload-list__item">
          <img :src="form.imageURL " class="el-upload-list__image" style="width: 100px; height: 100px;" />
        </div>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-button class="btuuu" type="primary" @click="handleBatchDelete">批量删除</el-button>

  <el-table
      :data="state.tableData"
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      style="width: 100%"
  >
    <el-table-column type="selection" width="35"/>
    <el-table-column property="name" label="商品名字" width="120"/>
    <el-table-column property="category" label="类别" width="100"/>
    <el-table-column property="price" label="价格" sortable width="80"/>
    <el-table-column property="stock" label="余量" sortable width="80"/>
    <el-table-column
        property="description"
        label="描述"
        width="150"
        show-overflow-tooltip
    />
    <el-table-column property="imageURL" label="商品图片" width="180">
      <template #default="scope">
        <img :src="scope.row.imageURL" style="width: 60px; height: auto;" />
      </template>
    </el-table-column>
    <el-table-column property="updatedAt" label="最后操作时间" width="120"/>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="openEditDialog(scope.$index, scope.row)">
          编辑
        </el-button>

        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog
      v-model="dialogFormVisible2"
      title="编辑商品信息"
      width="500"
  >
    <el-form :model="editform" ref="editForm">
    <el-form-item label="商品名" :label-width="formLabelWidth">
      <el-input v-model="editform.name" autocomplete="off" />
    </el-form-item>
    <el-form-item label="商品类别" :label-width="formLabelWidth">
      <el-select v-model="editform.category" placeholder="请选择类别">
        <el-option
            v-for="item in categoryOptions"
            :key="item"
            :label="item"
            :value="item"/>
      </el-select>
    </el-form-item>
    <el-form-item label="价格" :label-width="formLabelWidth">
      <el-input v-model="editform.price" autocomplete="off" />
    </el-form-item>
    <el-form-item label="库存" :label-width="formLabelWidth">
      <el-input v-model="editform.stock" autocomplete="off" />
    </el-form-item>
    <el-form-item label="商品描述" :label-width="formLabelWidth">
      <el-input v-model="editform.description" autocomplete="off" />
    </el-form-item>
    <el-form-item label="商品图片" :label-width="formLabelWidth">
      <el-upload
          class="upload-demo"
          drag
          :action="null"
          :http-request="uploadImage"
          :show-file-list="false"
          :before-upload="beforeUpload"
          accept="image/*"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">点击或拖拽上传图片</div>
        <div v-if="editform.imageURL " class="el-upload-list__item">
          <img :src="editform.imageURL " class="el-upload-list__image" style="width: 100px; height: 100px;" />
        </div>
      </el-upload>
    </el-form-item>
  </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <div class="demo-pagination-block">
    <div class="demonstration"></div>
    <el-pagination
        v-model="state.currentPage"
        :page-size="state.pageSize"
        :page-sizes="[5, 10, 20, 30, 40, 50]"
        :background="state.background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="state.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref,reactive, onMounted, watch } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus'
//获取类别
const categorySelect = ref('');
const categoryOptions = ref([]);
const fetchCategories = async () => {
  try {
    const response = await axios.get('/allCategories');
    categoryOptions.value = response.data.data;
  } catch (error) {
    console.error('Failed to fetch categories:', error);
  }
};
//获取商品数据
interface Product {
  productId: number;
  name: string;
  category: string;
  price: number;
  stock: number;
  description: string;
  imageURL: string;
  createdAt: Date;
  updatedAt: Date;
}
const state = reactive({
  tableData: [] as Product[],
  pageSize: 5,
  currentPage: 1,
  background: true,
  total: 0,
});
const fetchData = async (queryParams?: { description?: string; category?: string; low?: number; high?: number; }) => {
  try {
    const response = await axios.get('/productList', {
      params: {
        page: state.currentPage,
        pageSize: state.pageSize,
        ...queryParams, // 将查询参数添加到请求中
      },
    });
    const data = response.data;
    state.tableData = data.data.rows;
    state.total = data.data.total;
  } catch (error) {
    console.error('Failed to fetch data:', error);
  }
};
//页数
const handleSizeChange = (val: number) => {
  state.pageSize = val;
  state.currentPage = 1; // 重置到第一页
};
const handleCurrentChange = (val: number) => {
  state.currentPage = val;
};
// 处理查询的函数
const descriptionInput = ref('');
const priceLow = ref<number | null>(null);
const priceHigh = ref<number | null>(null);
// 添加一个响应式变量来存储查询参数
const searchParams = reactive<{
  description?: string;
  category?: string;
  low?: number;
  high?: number;
}>({});
const handleSearch = () => {
  searchParams.description = descriptionInput.value || undefined;
  searchParams.category = categorySelect.value || undefined;
  searchParams.low = priceLow.value !== null ? priceLow.value : undefined;
  searchParams.high = priceHigh.value !== null ? priceHigh.value : undefined;
  fetchData(searchParams);
};

onMounted(() => {
  fetchCategories(); // 在组件挂载时获取数据
  fetchData();
});
watch([() => state.currentPage, () => state.pageSize], () => {
  fetchData(searchParams);
});
//新增
const dialogFormVisible = ref(false);
const formLabelWidth = '140px';
const form = reactive({
  name: '',
  category: '',
  price: '',
  stock: '',
  description: '',
  imageURL: '', // 存储图片URL
});
// 上传图片
const uploadImage = async ({ file, onSuccess, onError }: { file: File; onSuccess: (url: string) => void; onError: (error: string) => void; }) => {
  const formData = new FormData();
  formData.append('image', file);
  try {
    const response = await axios.post('/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });
    if (response.data.code == 1) {
      form.imageURL= response.data.data;
      editform.value.imageURL = response.data.data;
      onSuccess(response.data.data);
    } else {
      onError(`上传失败: ${response.data.code}`);
    }
  } catch (error) {
    onError(`网络错误: ${error.message}`);
  }
};
// 上传前检查
const beforeUpload = (file: File): boolean => {
  const isLt2M = file.size / 1024 / 1024 < 2 && file.type.startsWith('image/');
  if (!isLt2M) {
    alert('上传图片大小不能超过2MB且只能是图片文件!');
  }
  return isLt2M;
};
//确认添加按钮函数
const handleAdd = async () => {
  try {
    const response = await axios.post('/productList', form);
    dialogFormVisible.value = false; // 关闭对话框
    ElMessage({message: '商品添加成功！', type: 'success',})
    fetchData();
  } catch (error) {
    ElMessage({message: '商品添加失败！', type: 'warning',})
    console.error('商品添加失败:', error);
  }
};
// 编辑
const dialogFormVisible2 = ref(false);
const editform = ref({
  name: '',
  category: '',
  price: '',
  stock: '',
  description: '',
  imageURL: '',
});
const openEditDialog = (index, row) => {
  axios.get(`/productList/${row.productId}`).then(response => {
    editform.value = response.data.data; // 直接赋值对象
    dialogFormVisible2.value = true;
  }).catch(error => {
    console.error("获取商品信息失败:", error);
  });
};

const submitEditForm = async () => {
  try {
    const response = await axios.put('/productList', editform.value);
      dialogFormVisible2.value = false; // 关闭对话框
      ElMessage({message: '商品修改成功！', type: 'success',})
      fetchData();
  } catch (error) {
    ElMessage({message: '商品修改失败！', type: 'error',})
    console.error("更新商品信息失败:", error);
  }
};
//单个删除函数
const handleDelete = async (index, row) => {
  try {
    const response = await axios.delete(`/productList/${row.productId}`);
    ElMessage({type: 'success', message: '删除成功',});
    fetchData();
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage({type: 'error', message: '删除失败，请稍后再试',});
  }
};
// 批量删除方法// 定义响应式状态
const selectedRows = ref<Array<{ productId: number }>>([]); // 选中行的数组
// 处理选中行变化的方法
const handleSelectionChange = (val: Array<{ productId: number }>) => {
  selectedRows.value = val;
};
//多个删除函数
const handleBatchDelete = async () => {
  const productIds = selectedRows.value.map(row => row.productId);
  try {
    const response = await axios.delete(`/productList/${productIds}`);
    ElMessage({type: 'success', message: '批量删除成功',});
    fetchData();
  } catch (error) {
    console.error('批量删除失败:', error);
    ElMessage({type: 'error', message: '批量删除失败，请稍后再试',});
  }
};
</script>
<style>
.cell{
  text-align: center;
}
.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.btuuu{
  margin:0px 20px 10px 0px;
}
</style>